package com.fingard.dsp.bank.directbank.hebbank01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.Date;

public class HEBBANK01Transaction extends HEBBANK01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        String tmpRespInfo = "";
        StringBuilder message = new StringBuilder();

        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            //按自然月循环查询
            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while (tmpIntDateFrom <= tmpIntDateTo) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                boolean flag = true;
                while (flag) {
                    int beginPos = 1;
                    int showNum = 10;
                    HEBBANK01Header bankHeader = new HEBBANK01Header();
                    bankHeader.bsnCode = "CBE012";
                    bankHeader.serialNo = p_req7516.reqHeader.reqSeqID;
                    //新建发送银行报文
                    XmlTextWriter xmlWriter = new XmlTextWriter();
                    writeCommonHeader(xmlWriter, bankHeader);
                    xmlWriter.writeElementString("areaCode", "0000");
                    xmlWriter.writeStartElement("ReqParam");
                    xmlWriter.writeElementString("Account_num", p_req7516.actNum);
                    xmlWriter.writeElementString("Account_cur", p_req7516.actCur);
                    xmlWriter.writeElementString("Begin_date", Format.Date8Format.format(tmpCalendarFrom.getTime()));
                    xmlWriter.writeElementString("End_date", Format.Date8Format.format(tmpCalendarTo.getTime()));
                    xmlWriter.writeElementString("turnPageBeginPos", beginPos + "");
                    xmlWriter.writeElementString("turnPageShowNum", showNum + "");
                    xmlWriter.writeEndElement();
                    xmlWriter.writeEndDocument();
                    beginPos += showNum;

                    String[] bankResult = sendToBank(xmlWriter.toXmlString(), bankHeader);
                    if (bankResult[0].length() == 0) {
                        String[] result = bankResult[1].split("\\|");
                        if ("0000".equals(result[0])) {
                            StringBuilder tmpSbMsg = new StringBuilder();
                            String xmlStr = bankResult[1].substring(bankResult[1].indexOf("|#") + 2);
                            XmlTextReader tmpBkReader = loadBankRespXmlReader(xmlStr, tmpSbMsg);
                            if (tmpBkReader != null) {
                                while (tmpBkReader.read("/SCCBEBankData/opRep/serialNo/opResult/list/row")) {
                                    RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                    XElement tmpRecord = tmpBkReader.readedXElement;
                                    tmpRetDetail.actNum = p_req7516.actNum;
                                    tmpRetDetail.recAccNum = tmpRecord.getSingleText("Rec_Account_num");//收方账号
                                    tmpRetDetail.recAccName = tmpRecord.getSingleText("Unit1_name");//收方户名
                                    tmpRetDetail.recAccBank = "";//收方银行
                                    tmpRetDetail.tranAmt = tmpRecord.getSingleText("Txamt");//交易金额
                                    tmpRetDetail.accBal = tmpRecord.getSingleText("Balance");//账户余额
                                    tmpRetDetail.cdFlag = tmpRecord.getSingleText("Sign").equals("0") ? "1" : "2";//借贷标志 0-借记1-贷记
                                    String tranDate = tmpRecord.getSingleText("Txdate");//交易日期yyyyMMdd
                                    tmpRetDetail.tranDate = tranDate.substring(0, 4) + "-" + tranDate.substring(4, 6) + "-" + tranDate.substring(6, 8);
                                    String tranTime = tmpRecord.getSingleText("Txtime");//交易时间yyyyMMddhhmmss
                                    tmpRetDetail.tranTime = tranTime.substring(0, 4) + "-" + tranTime.substring(4, 6) + "-" + tranTime.substring(6, 8) + " " + tranTime.substring(8, 10) + ":" + tranTime.substring(10, 12) + ":" + tranTime.substring(12, 14);
                                    tmpRetDetail.usage = tmpRecord.getSingleText("payUse");
                                    tmpRetDetail.abstr = tmpRecord.getSingleText("Trans_abstr");//摘要（对账码）
                                    retAts.writeRetDetailWithoutRespCode(tmpRetDetail);
                                }
                            } else {
                                tmpRespInfo = "查询时间：" + Format.Date8Format.format(tmpCalendarFrom.getTime()) + "到" + Format.Date8Format.format(tmpCalendarTo.getTime()) + ",查询失败：" + ";";
                                message.append(tmpRespInfo);
                            }
                        } else {
                            tmpRespInfo = "查询时间：" + Format.Date8Format.format(tmpCalendarFrom.getTime()) + "到" + Format.Date8Format.format(tmpCalendarTo.getTime()) + ",查询失败：" + result[1] + ";";
                            message.append(tmpRespInfo);
                        }
                    } else {
                        tmpRespInfo = "查询时间：" + Format.Date8Format.format(tmpCalendarFrom.getTime()) + "到" + Format.Date8Format.format(tmpCalendarTo.getTime()) + ",查询失败：" + bankResult[1] + ";";
                        message.append(tmpRespInfo);
                    }
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);//下个月
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
            retAts.writeEnd();
            return retAts;
        }
        if (retAts.getWrittenRdCount() == 0 && message.length() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空！");
        } else if (retAts.getWrittenRdCount() > 0 && message.length() > 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo(message.toString());
        } else if (retAts.getWrittenRdCount() == 0 && message.length() > 0) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(message.toString());
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        p_req7516.actArea = p_req7515.actArea;
        Date date = new Date();
        p_req7516.dateFrom = Format.Date8Format.format(date);
        p_req7516.dateTo = Format.Date8Format.format(date);
        return d_7516_HisTrans(p_req7516);
    }
}
